package cn.wit.summit.chwan.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.cos.COSClient;
import com.tencent.cos.COSClientConfig;
import com.tencent.cos.common.COSEndPoint;
import com.tencent.cos.model.COSRequest;
import com.tencent.cos.model.COSResult;
import com.tencent.cos.model.PutObjectRequest;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import cn.wit.summit.chwan.models.response.CodeloginRespone;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.BuildRequestUtils;
import cn.wit.summit.chwan.net.NetCallBack;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.net.okhttplib.HttpInfo;
import cn.wit.summit.chwan.net.okhttplib.OkHttpUtil;
import cn.wit.summit.chwan.net.okhttplib.callback.Callback;
import cn.wit.summit.chwan.ui.activity.SettingActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Cos人图片上传类
 */
public class TCUploadHelper {
    private static final String TAG = "TCUploadHelper";

    private final static int MAIN_CALL_BACK = 1;
    private final static int MAIN_PROCESS = 2;
    private final static int UPLOAD_AGAIN = 3;

    private Context mContext;
    private OnUploadListener mListerner;
    private static Handler mMainHandler;

    public TCUploadHelper(final Context context, OnUploadListener listener) {
        mContext = context;
        mListerner = listener;

        mMainHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case MAIN_CALL_BACK:
                        if (mListerner != null) {
                            mListerner.onUploadResult(msg.arg1, (String) msg.obj);
                        }
                        break;
                    case UPLOAD_AGAIN:
                        Bundle taskBundle = (Bundle) msg.obj;
//                        doUploadCover(taskBundle.getString("path", ""), taskBundle.getString("netUrl", ""), taskBundle.getString("sig", ""), false);
                    default:
                        break;
                }
                return false;
            }
        });
    }

//    private String createNetUrl() {
//        return "/live_cover/" + TCUserInfoMgr.getInstance().getUserId() + "_" + System.currentTimeMillis() + ".jpg";
//    }

    private static void uploadFile(final String path, String sig, String appid, String bucket, String directory, Activity activity) {
//        String appid = TCConstants.COS_APPID;
//    String appid =  "腾讯云注册的appid";
        Context context = activity;
        String peristenceId = "";

//创建COSClientConfig对象，根据需要修改默认的配置参数
        COSClientConfig config = new COSClientConfig();
//如设置园区
        config.setEndPoint(COSEndPoint.COS_GZ);

        COSClient cos = new COSClient(context, appid, config, null);
//        String bucket = TCConstants.COS_BUCKET;
//        String cosPath = "/live_cover/" + new File(path).getName();
        final String cosPath = File.separator + directory + File.separator + new File(path).getName();
        String srcPath = path;
        String sign = sig;

        PutObjectRequest putObjectRequest = new PutObjectRequest();
        putObjectRequest.setBucket(bucket);
        putObjectRequest.setCosPath(cosPath);
        putObjectRequest.setSrcPath(srcPath);
        putObjectRequest.setSign(sign);
        putObjectRequest.setInsertOnly("0");
        putObjectRequest.setListener(new com.tencent.cos.task.listener.IUploadTaskListener() {
            @Override
            public void onProgress(COSRequest cosRequest, long l, long l1) {

            }

            @Override
            public void onCancel(COSRequest cosRequest, COSResult cosResult) {
                Message msg = new Message();
                msg.what = MAIN_CALL_BACK;
                msg.arg1 = cosResult.code;
                msg.obj = cosResult.msg;
                mMainHandler.sendMessage(msg);
            }

            @Override
            public void onSuccess(COSRequest cosRequest, COSResult cosResult) {
                Log.w(TAG, "uploadCover do upload onSuccess,");
                Message msg = new Message();
                msg.what = MAIN_CALL_BACK;
                msg.arg1 = 0;
//                msg.obj = cosResult.msg;
                msg.obj = cosPath;

                mMainHandler.sendMessage(msg);
            }

            @Override
            public void onFailed(COSRequest cosRequest, COSResult cosResult) {
                Log.w(TAG, "uploadCover do upload fail,");
                Message msg = new Message();
                msg.what = MAIN_CALL_BACK;
                msg.arg1 = cosResult.code;
                msg.obj = cosResult.msg;
                mMainHandler.sendMessage(msg);
            }
        });
        cos.putObject(putObjectRequest);
    }

    private void doUploadCover(final String path, final String sig, final String appid, final String bucket, final String directory) {
        new Thread() {
            @Override
            public void run() {
//                uploadFile(path, sig, appid, bucket, directory);
            }
        }.start();
    }

    public void uploadCover(final String filePath, String uid, String token, final Activity activity) {
//        Map<String, String> params = new HashMap<>();
////        params.put("Action", "UploadCover");
//        params.put("uid", uid + "");
//        params.put("token", token);
//        OkHttpClientManager.ResultCallback callback = new OkHttpClientManager.ResultCallback<PaMgrBean.Response<PaMgrBean.Response.UplocadCover>>() {
//            @Override
//            public void onError(Request request, Exception e) {
//                if (mListerner != null) {
//                    mListerner.onUploadResult(-1, null);
//                }
//            }
//
//            @Override
//            public void onResponse(PaMgrBean.Response<PaMgrBean.Response.UplocadCover> response) {
//                if (response != null && response.getError() == 0) {
//                    PaMgrBean.Response.UplocadCover respons = response.getData();
//                    String appid = respons.getAppId();
//                    String signature = respons.getSignature();
//                    String bucket = respons.getBucket();
//                    String directory = respons.getUploadDir();
//
//                    uploadFile(filePath, signature, appid, bucket, directory);
//                } else {
//                    onError(null, null);
//
//                }
//            }
//        };
//        postAsyn(RpcConstant.getChangeIcon+"interface/getcossign", activity, filePath);

    }

    public static class UplocadCover {
        //            private String signature;
//            private String file;
        private String appId;
        private String bucket;
        private String signature;
        private String uploadDir;//创传文件的目录
        private String file;//下载文件的目录

        public String getSignature() {
            return signature;
        }

        public void setSignature(String signature) {
            this.signature = signature;
        }

        public String getFile() {
            return file;
        }

        public void setFile(String file) {
            this.file = file;
        }

        public String getAppId() {
            return appId;
        }

        public void setAppId(String appId) {
            this.appId = appId;
        }

        public String getBucket() {
            return bucket;
        }

        public void setBucket(String bucket) {
            this.bucket = bucket;
        }

        public String getUploadDir() {
            return uploadDir;
        }

        public void setUploadDir(String uploadDir) {
            this.uploadDir = uploadDir;
        }
    }

    public static class Response<T> {
        private int error;
        private T data;

        public int getError() {
            return error;
        }

        public void setError(int error) {
            this.error = error;
        }

        public T getData() {
            return data;
        }

        public void setData(T data) {
            this.data = data;
        }

        public Response() {
        }

        public Response(int error, T data) {
            this.error = error;
            this.data = data;
        }
    }


//    private static void postAsyn(String url, final Activity activity, final String filePath) {
//        OkHttpUtil.getDefault(activity).doPostAsync(BuildRequestUtils.getInstance(activity).getUploadData(url,
//                AccountUtil.getInstance().getUid(), AccountUtil.getInstance().getToken()),
//                new Callback() {
//                    @Override
//                    public void onCache(HttpInfo info) throws IOException {
//
//                    }
//
//                    @Override
//                    public void onSuccess(HttpInfo info) throws IOException {
////                        String rp = info.getRetDetail();
//
//                        Type type = new TypeToken<ResponseBase<UplocadCover>>() {
//                        }.getType();
//                        ResponseBase<UplocadCover> responseBean = info.getRetDetail(type);
//                        UplocadCover respons = responseBean.getData_info();
//                        String appid = respons.getAppId();
//                        String signature = respons.getSignature();
//                        String bucket = respons.getBucket();
//                        String directory = respons.getUploadDir();
//
//                        uploadFile(filePath, signature, appid, bucket, directory, activity);
//
//                    }
//
//                    @Override
//                    public void onFailure(HttpInfo info) throws IOException {
//                       ToastUtils.getInstance(activity).showToastSystem("失败！！！");
//                    }
//                });
//    }

    public interface OnUploadListener {
        void onUploadResult(int code, String url);
    }

}
